package cn.com.headfree.welfare.controller;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.excel.imports.ExcelImportService;
import cn.com.headfree.base.controller.ExBaseController;
import cn.com.headfree.base.controller.ResultData;
import cn.com.headfree.entity.TOrgDept;
import cn.com.headfree.entity.isc.User;
import cn.com.headfree.mouldshow.controller.HumanDataImportController;
import cn.com.headfree.vo.SysDictionaryInfoVo;
import cn.com.headfree.welfare.dao.FlNcsgsxdjhDao;
import cn.com.headfree.welfare.entity.FlNcsgsxdjh;
import cn.com.headfree.welfare.entity.FlNcsgsxdjh;
import cn.com.headfree.welfare.entity.Vo.TOrgDeptVo;
import cn.com.headfree.welfare.entity.Vo.dictionaryVo;
import cn.com.headfree.welfare.entity.testa;
import cn.com.headfree.welfare.service.FlNcsgsxdjhService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.gta.edu.sdk.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * 年初省公司下达计划情况
 * @author gaohao
 * @since 2021-12-15 14:53:13
 */
@RestController
@RequestMapping("flNcsgsxdjh")
public class FlNcsgsxdjhController extends ExBaseController {
    private static final Logger LOG = LogManager.getLogger(FlNcsgsxdjhController.class);
    /**
     * 服务对象
     */
    @Resource
    private FlNcsgsxdjhService flNcsgsxdjhService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public ResultData selectOne(Integer id, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            FlNcsgsxdjh flNcsgsxdjh=this.flNcsgsxdjhService.queryById(id);
            String json= JSON.toJSONString(flNcsgsxdjh);//关键
            LOG.info(json);
            if(flNcsgsxdjh!=null)
            {
                result.setSuccess(true);
                result.setData(flNcsgsxdjh);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("查询失败");
            }


        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }

    /**
     * 新增数据
     *
     * @param flNcsgsxdjh 实例对象
     * @return 实例对象
     */
    @PostMapping("insert")
    public ResultData insert(@RequestBody FlNcsgsxdjh flNcsgsxdjh, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        //获取当前登录用户所在组织机构的一级部门
        String deptid=get3DeptId(user.getBaseOrgId());
        if(deptid==null){
            result.setSuccess(false);
            result.setErrorMsg("当前登录人部门信息获取异常!");
            return result;
        }
        user.setBaseOrgId(deptid);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            //flNcsgsxdjh.setOrgId(user.getBaseOrgId());
            flNcsgsxdjh.setCreaterId(user.getId());
            flNcsgsxdjh.setCreaterName(user.getName());
            flNcsgsxdjh.setCreateTime(new Date());
            flNcsgsxdjh.setDelSign(0);
            flNcsgsxdjh=flNcsgsxdjhService.insert(flNcsgsxdjh);
            if(flNcsgsxdjh!=null)
            {
                result.setSuccess(true);
                result.setData(flNcsgsxdjh);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("添加失败");
            }


        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }

    /**
     * 修改数据
     *
     * @param flNcsgsxdjh 实例对象
     * @return 实例对象
     */
    @PostMapping("update")
    public ResultData update(@RequestBody FlNcsgsxdjh flNcsgsxdjh, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);

        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            //flNcsgsxdjh.setOrgId(user.getBaseOrgId());
            flNcsgsxdjh.setUpdaterId(user.getId());
            flNcsgsxdjh.setUpdaterName(user.getName());
            flNcsgsxdjh.setCreateTime(new Date());
            flNcsgsxdjh=this.flNcsgsxdjhService.update(flNcsgsxdjh);
            if(flNcsgsxdjh!=null)
            {
                result.setSuccess(true);
                result.setData(flNcsgsxdjh);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("修改失败");
            }
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @PostMapping("deleteById")
    public ResultData deleteById(Integer id, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            FlNcsgsxdjh flNcsgsxdjh=this.flNcsgsxdjhService.queryById(id);
            if(flNcsgsxdjh==null){
                result.setSuccess(false);
                result.setData("未查询到数据");
                return result;
            }
            //flNcsgsxdjh.setOrgId(user.getBaseOrgId());
            flNcsgsxdjh.setUpdaterId(user.getId());
            flNcsgsxdjh.setUpdaterName(user.getName());
            flNcsgsxdjh.setCreateTime(new Date());
            flNcsgsxdjh.setDelSign(1);
            flNcsgsxdjh=this.flNcsgsxdjhService.update(flNcsgsxdjh);
            if(flNcsgsxdjh!=null)
            {
                result.setSuccess(true);
                result.setData(flNcsgsxdjh);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("修改失败");
            }
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }


    /**
     * 通过实体作为筛选条件查询
     *
     * @param flNcsgsxdjh 实例对象
     * @return 对象列表
     */
    @PostMapping("queryAll")
    public ResultData queryAll( @RequestBody  FlNcsgsxdjh flNcsgsxdjh, HttpServletRequest request) {
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            PageInfo<FlNcsgsxdjh> list=this.flNcsgsxdjhService.queryAll(flNcsgsxdjh);
            if(flNcsgsxdjh!=null)
            {
                result.setSuccess(true);
                result.setData(list);
            }else {
                result.setSuccess(false);
                result.setErrorMsg("修改失败");
            }
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }
    /**
     * 数据批量导入
     */
    @PostMapping("/importDatas")
    public ResultData importDatas(HttpServletRequest request, HttpServletResponse response, MultipartFile file,String year,String orgId){
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            result=this.flNcsgsxdjhService.importRollExcel(file,request,response,user,year,orgId);
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }
    /**
     * 查询字典
     */
    @GetMapping("/selectDict")
    public ResultData selectDict(HttpServletRequest request, String value){
        ResultData result = new ResultData();
        User user = this.getLoginUserInfo(request);
        if((null != user)&&(StringUtils.isNotBlank(user.getId()))) {
            result.setSuccess(true);
            List<dictionaryVo> list=this.flNcsgsxdjhService.selectDict(value);
            result.setData(list);
        }else {
            LOG.error("获取统一权限用户信息异常");
            result.setSuccess(false);
            result.setErrorMsg("获取统一权限用户信息异常");
        }
        return result;
    }



    /**
     * 根据登录人组织机构,获取对应的部门信息
     *
     * @return
     */
    @RequestMapping("/getDeptsByOrgId")
    @ResponseBody
    public ResultData getDeptsByOrgId(HttpServletRequest req,String type) {
        ResultData result = new ResultData();
        try {
            //获取登陆用户信息
            User user = getLoginUserInfo(req);
            if(user==null) {
                result.setSuccess(false);
                result.setErrorMsg("当前登录人信息获取异常!");
                return result;
            }

            //获取当前登录用户所在组织机构的一级部门

            String deptid=get3DeptId(user.getBaseOrgId());

            if(type.equals("1")){
                deptid="10330026";
            }
            if(deptid==null){
                result.setSuccess(false);
                result.setErrorMsg("当前登录人部门信息获取异常!");
                return result;
            }
            user.setBaseOrgId(deptid);
//            user.setBaseOrgId("10330026");
            List<TOrgDeptVo> depts = flNcsgsxdjhService.getDeptsByOrgId(user);
            List<TOrgDeptVo> Tree=  listToTree(depts);
            if(type.equals("1")){
                result.setData(depts);
            }else {
                result.setData(Tree);
            }

        } catch (Exception e) {
            result.setErrorMsg("模糊查询信息异常");
            result.setSuccess(false);
            LOG.error("模糊查询信息异常", e);
        }
        return result;
    }


    private static List<TOrgDeptVo> listToTree(List<TOrgDeptVo> oldList){
        Map<String,Object> newMap = new HashMap<>();
        List<TOrgDeptVo> newList = new ArrayList<>();
        for (TOrgDeptVo treeDto : oldList){
            newMap.put(treeDto.getId(),treeDto);
        }
        for (TOrgDeptVo treeDto : oldList){
            TOrgDeptVo parent = (TOrgDeptVo) newMap.get(treeDto.getPId());
            if (parent != null){
                if (parent.getChildren() == null){
                    List<TOrgDeptVo> ch = new ArrayList<>();
                    ch.add(treeDto);
                    parent.setChildren(ch);
                }else {
                    List<TOrgDeptVo> ch = parent.getChildren();
                    ch.add(treeDto);
                    parent.setChildren(ch);
                }
            }else {
                newList.add(treeDto);
            }
        }
        return newList;
    }

    /**
     * 获取流出部门
     * @param req
     * @return
     */
    @RequestMapping("/getDepInfByOrgId")
    @ResponseBody
    public ResultData getDepInfByOrgId(HttpServletRequest req){
        ResultData result = new ResultData();
        try {
            //获取登陆用户信息
            User user = getLoginUserInfo(req);
            if (user == null) {
                result.setSuccess(false);
                result.setErrorMsg("当前登录人信息获取异常!");
                return result;
            }
            String deptid=get3DeptId(user.getBaseOrgId());
            TOrgDept depts = flNcsgsxdjhService.getPdeptid(deptid);
            result.setSuccess(true);
            result.setData(depts);

        }catch (Exception e){
            result.setErrorMsg("模糊查询信息异常");
            result.setSuccess(false);
            LOG.error("模糊查询信息异常", e);
        }
        return result;
    }

    private String get3DeptId(String orgId){
        TOrgDept depts = flNcsgsxdjhService.getPdeptid(orgId);
        String re="";
        if(depts==null){
            return null;
        }
        if(Integer.valueOf(depts.getLevel())>2){
            re=get3DeptId(depts.getpId());
        }else {
            if(depts.getName().indexOf("公司")<0){
                re= get3DeptId(depts.getpId());
            }else {
                re=depts.getId();
            }
        }
        return re;
    }


}
